import { useState, useEffect } from 'react';
import { message } from 'antd';

import SparkChannel, { EE } from 'src/ipc/sparkchannel'
import { DATE_FMT } from 'src/core/common'
import SpdTable from 'src/component/SpdTable'

const columns = [
  {
    title: '序号',
    dataIndex: 'key',
    key: 'key',
    width: 70,
  },
  {
    title: '类型',
    dataIndex: 'type_desc',
    key: 'type_desc',
    width: 120,
  },
  {
    title: '时间',
    dataIndex: 'time',
    key: 'time',
    width: 190,
  },
  {
    title: '级别',
    dataIndex: 'level',
    key: 'level',
    width: 70,
  },
  {
    title: '设备对象',
    dataIndex: 'device',
    key: 'device',
    width: 150,
  },
  {
    title: '告警内容',
    dataIndex: 'desc',
    key: 'desc',
  },
];

const PAGE_SIZE = 1000;

const EventTable = () => {
  const [queryParams, setQueryParams] = useState();
  const [tableData, setTableData] = useState([]);
  const [loading, setLoading] = useState(false);
  const [pageCurrent, setPageCurrent] = useState(1);
  const [pageTotal, setPageTotal] = useState(0);

  const fetchData = async (query, page) => {
    setLoading(true);

    try {
      const channel = await SparkChannel();
      const resp = await channel.request_get_event_list({
        from: query.from.format(DATE_FMT),
        to: query.to.format(DATE_FMT),
        type_list: query.type_list.join(','),
        device_list: query.device_list.join(','),
        fuzzy_search: query.fuzzy_search,
        page: page,
        rows: PAGE_SIZE,
      });
      const { event_list, total } = resp.data;

      const start = page * PAGE_SIZE;
      event_list.forEach((e, index) => {
        e.key = start + index + 1;
        e.device = [e.bay_desc, e.device_desc].filter(Boolean).join('/');
      });
      setTableData(event_list);
      setPageTotal(total);
    } catch (err) {
      console.log('request_get_event_list fail', err);
      message.error('加载数据失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    async function handler(query) {
      setQueryParams(query);
      setPageCurrent(1);
      fetchData(query, 0);
    }
    EE.on('list-hisevent', handler);

    return function cleanup() {
      EE.removeListener('list-hisevent', handler);
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const handleTableChange = (pagination, filters, sorter) => {
    setPageCurrent(pagination.current);
    fetchData(queryParams, pagination.current - 1);
  };

  return (
    <SpdTable
      bordered
      columns={columns}
      loading={loading}
      dataSource={tableData}
      pagination={{
        current: pageCurrent,
        pageSize: PAGE_SIZE,
        total: pageTotal,
        showSizeChanger: false,
      }}
      onChange={handleTableChange} />
  )
};
export default EventTable;